import request from "./http.js"
console.log(request)

//微信授权
const isWechat = function() {
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
//方法:用来提取code
const getUrlCode = function(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
			''
		])[1]
		.replace(/\+/g, '%20')) || null
}
//检查浏览器地址栏中微信接口返回的code
const checkWeChatCode = async function() {
	let code = await getUrlCode('code')
	// let openid = uni.getStorageSync("userInfo").openid?uni.getStorageSync("userInfo").openid:null
	let userInfo = uni.getStorageSync("userInfo")
	console.log(userInfo)
	let openid = userInfo?userInfo.openid:null
	if (code||openid) {
		const gUser =  await getOpenidAndUserinfo(code,openid)
		if(gUser.status==1){
			afterLogin(gUser)
		}
	} else {
	 await getWeChatCode()
	}
}
//请求微信接口，用来获取code
const getWeChatCode = function() {
	let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
	// let appid = 'wx3da9056cdd06e96c'
	request.post("/api/Serviceuserapi/getCodeUrl").then(res=>{
		window.location.href = res.result
	})
	// uni.request({
	// 	url:"http://nhbdshangcheng.duobashuzi.com/index.php/api/Serviceuserapi/getCodeUrl",
	// 	method:"post",
	// 	success(res){
	// 		console.log(res)
	// 	}
	// })

	//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	// window.location.href =
	// 	"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
	// 	appid +
	// 	"&redirect_uri=" +
	// 	local +
	// 	"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
}
//把code传递给后台接口，静默登录
const getOpenidAndUserinfo = async function(code,openid) {
	return new Promise(function(reslove,reject){
		request.post("/api/Serviceuserapi/getUserInfoFunc",{code,openid}).then(res=>{
			
			reslove(res)
		})
	})
	
}
/*微信登录相关  end*/
const afterLogin = async function(res) {
	// let user = res.data.user
	console.log(res)
	await uni.setStorageSync("userInfo",res.result)
	// let u = {
	// 	avatar: user.avatar ? user.avatar : this.avatar,
	// 	mobile: user.mobile,
	// 	nickname: user.nickname ? user.nickname : ''
	// }
	// uni.setStorage({
	// 	key: 'u',
	// 	data: u,
	// 	success: () => {

	// 		let url = uni.getStorageSync('redirect')
	// 		uni.reLaunch({
	// 			url: url ? url : '/pages/index/index'
	// 		})
	// 	}
	// });
}
export {
	checkWeChatCode
}
